package com.puboot.common.util;

import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @Description
 * @Author 申紫微
 * @Data 2020-02-14 13:55:46
 * @Version 1.0
 */
@Component("ftpUtil")
@Data
public class FTPUtil {

    @Value("${ftp.server.ip}")
    private String ip;
    @Value("${ftp.server.port}")
    private int port;
    @Value("${ftp.user}")
    private String user;
    @Value("${ftp.pass}")
    private String pwd;
    @Value("${ftp.server.path}")
    private String ftpPath;

    private static FTPClient ftpClient;

    private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    /**
     * 上传文件
     *
     * @author 卫江涛/wjt
     * @date 2019年8月19日
     */
    public static boolean upload(String remotePath, List<File> fileList) throws IOException {
        FTPUtil ftp = (FTPUtil) SpringContextUtils.getBean("ftpUtil");
        logger.info("开始连接ftp服务器");
        boolean result = ftp.uploadFile(remotePath, fileList);
        logger.info("开始连接ftp服务器,结束上传,上传结果:{}", result);
        return result;
    }

    private boolean uploadFile(String remotePath, List<File> fileList) throws IOException {

        // 创建目录

        boolean uploaded = true;
        FileInputStream fis = null;
        // 连接FTP服务器
        if (connectServer()) {
            try {
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                for (File fileItem : fileList) {
                    fis = new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(), fis);
                }

            } catch (IOException e) {
                logger.error("上传文件异常", e);
                uploaded = false;
                e.printStackTrace();
            } finally {
                fis.close();
                ftpClient.disconnect();
            }
        } else {
            return false;
        }
        return uploaded;
    }

    /**
     * 连接ftp
     *
     * @author 卫江涛/wjt
     * @date 2019年8月19日
     */
    private boolean connectServer() {

        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user, pwd);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常", e);
        }
        return isSuccess;
    }
}